<template>
	<view class="ImageDetail">
		<view class="content">
			<scroll-view
				class="scroll"
				:scroll-top="scrollTop"
				scroll-y="true"
				lower-threshold="50"
				@scrolltolower="lower"
			>
				<view>
					<view class="img_box">
						<view class="img">
							<image style="width: 100vw" :src="imgUrl" mode="widthFix" show-menu-by-longpress></image>
						</view>
						<view class="img_mask" @click="handlePreview"></view>
					</view>

					<view class="sticky" :style="[style]">
						<view class="toolbar">
							<view class="tags" v-if="tags.length">
								<view class="edit_btn" @click="handleEdit" v-if="!isEdit">
									<u-icon name="edit-pen" color="#55acee" size="40rpx"></u-icon>
								</view>
								<view class="back_btn" @click="isEdit = false" v-else>
									<image
										style="width: 60rpx; height: 60rpx;"
										src="../../static/back-icon.png"
										mode="widthFix"
									></image>
								</view>

								<view style="text-align: center;">
									<view class="tag_item">
										<Tag :text="category" color="#55acee" @click="isUpdate('1')">
											<view class="tag_icon" v-if="isEdit">
												<u-icon name="edit-pen" color="#55acee" size="32rpx"></u-icon>
											</view>
										</Tag>
									</view>
									<view class="tag_item">
										<Tag :text="appName" color="#55acee" @click="isEdit ? isUpdate('2') : clickTag(appName)">
											<view class="tag_icon" v-if="isEdit">
												<u-icon name="edit-pen" color="#55acee" size="32rpx"></u-icon>
											</view>
										</Tag>
									</view>
								</view>
								<view class="tag_list">
									<view class="tag_item" v-if="isEdit" @click="$refs.tagPopupEdit.open()">
										<view class="Tag">
											<view class="tag-wrap"><text>+ 新标签</text></view>
										</view>
									</view>

									<view class="tag_item" v-for="(item, index) in tags" :key="index">
										<Tag :text="item.name" @click="isEdit ? isUpdate('3', item) : clickTag(item.name)">
											<view class="tag_icon" v-if="isEdit">
												<uni-icons type="closeempty" size="32rpx" color="#FF8494"></uni-icons>
											</view>
										</Tag>
									</view>
								</view>
							</view>
							<view class="btns">
								<view v-if="favoriteStatus" class="img_btn collect" @click="cancelCollect">已收藏</view>
								<view v-else class="img_btn collect" @click="collect">收藏</view>
								<view class="img_btn save" @click="saveImage">下载</view>
								<button class="share_btn" :plain="true" open-type="share">
									<u-icon name="share-square" size="60rpx"></u-icon>
								</button>
							</view>
						</view>
					</view>

					<view class="more">
						<view class="more_title">更多此类型图片</view>
						<view class="more_list">
							<waterfallsFlow
								v-if="showWaterfall"
								ref="waterfallsFlow"
								imageSrcKey="small_url"
								:single="true"
								:list="list"
								@image-click="handleImg"
							/>
						</view>
					</view>

					<view class="list_loading" v-if="list.length <= 0 && tags.length">
						<u-loading-icon></u-loading-icon>
					</view>
					<view class="more_loading"><uni-load-more :status="moreLoading"></uni-load-more></view>
				</view>
			</scroll-view>

			<!-- 收藏弹窗 -->
			<uni-popup ref="popup" type="bottom" :safe-area="false">
				<view class="collect_popup">
					<view class="collect_top">
						<view class="icon">
							<uni-icons type="closeempty" size="40rpx" @click="$refs.popup.close()"></uni-icons>
						</view>
						<view class="title">收藏</view>
					</view>
					<view class="collect_list">
						<view class="new_collect" v-if="newFolder.length">
							<view class="title">最近收藏</view>
							<view class="list">
								<view
									class="collect_item"
									v-for="item in newFolder"
									:key="item.id"
									@click="collectAsset(item.id)"
								>
									<view class="cover">
										<image
											v-if="item.amount && item.cover_path"
											style="width: 100%;"
											:src="getAssetUrl(item.cover_path[0])"
											mode="widthFix"
										></image>
									</view>
									<text>{{ item.name }}</text>
								</view>
							</view>
						</view>
						<view class="all_collect">
							<view class="title">全部收藏夹</view>
							<view class="list">
								<view
									class="collect_item"
									v-for="item in allFolder"
									:key="item.id"
									@click="collectAsset(item.id)"
								>
									<view class="cover">
										<image
											v-if="item.amount && item.cover_path"
											style="width: 100%;"
											:src="getAssetUrl(item.cover_path[0])"
											mode="widthFix"
										></image>
									</view>
									<text>{{ item.name }}</text>
								</view>
							</view>
						</view>
					</view>
					<view class="create_folder">
						<view class="input_box">
							<view class="input">
								<u--input
									v-model="folderName"
									placeholder="请输入收藏夹名称"
									border="bottom"
									clearable
								></u--input>
							</view>
							<view class="create_btn" @click="createFolder">创建</view>
						</view>
					</view>
				</view>
			</uni-popup>

			<!-- 编辑弹窗 -->
			<uni-popup ref="popupEdit" type="bottom" :safe-area="false">
				<view class="edit_popup">
					<view v-if="!isSuccess">
						<view class="edit_top">
							<view class="title">“{{ category }}”分类错误？</view>
							<view class="icon">
								<uni-icons type="closeempty" size="40rpx" @click="$refs.popupEdit.close()"></uni-icons>
							</view>
						</view>

						<view class="edit_input">
							<view class="input_box">
								<view class="input">
									<u--input
										v-model="categoriesName"
										placeholder="请选择正确分类"
										border="bottom"
										clearable
										@input="search()"
									></u--input>
								</view>
								<view class="create_btn" @click="updateCategories">提交</view>
							</view>
						</view>

						<view v-if="showCategoriesList">
							<view class="loading" v-if="categoriesLoading"><u-loading-icon></u-loading-icon></view>
							<view class="edit_list" v-else>
								<view class="list">
									<view
										class="item"
										v-for="item in categoriesList"
										:key="item.id"
										@click="handleCategorysItem(item)"
									>
										<text>{{ item.name }}</text>
									</view>
								</view>
							</view>
						</view>
					</view>

					<view class="" v-if="isSuccess">
						<view class="edit_top">
							<view class="title"></view>
							<view class="icon">
								<uni-icons type="closeempty" size="40rpx" @click="$refs.popupEdit.close()"></uni-icons>
							</view>
						</view>
						<view class="success_main">
							<image
								src="../../static/result-ico.png"
								style="width: 120rpx;height: 120rpx;margin-bottom: 40rpx;"
								mode="widthFix"
							></image>
							<view v-if="categoriesName">已提交修改为“{{ categoriesName }}”，感谢您的贡献！</view>
							<view v-else>提交成功，感谢您的贡献！</view>
							<view style="width: 602rpx;height: 2rpx;background: #EFEFEF;margin: 40rpx 0;"></view>
							<view class="users">
								<text style="color: #A0A0A0;">相同反馈（达到一定数量后生效）：</text>
								<view
									style="display: inline-block;"
									v-for="(item, index) in categoryUpdateData"
									:key="item.id"
								>
									<text v-if="index != 'type'">
										{{ index == 0 ? item.user.nick_name : ',' + item.user.nick_name }}
									</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</uni-popup>

			<!-- app编辑弹窗 -->
			<uni-popup ref="appPopupEdit" type="bottom" :safe-area="false">
				<view class="edit_popup">
					<view v-if="!isSuccess">
						<view class="edit_top">
							<view class="title">“{{ appName }}”名称错误？</view>
							<view class="icon">
								<uni-icons
									type="closeempty"
									size="40rpx"
									@click="$refs.appPopupEdit.close()"
								></uni-icons>
							</view>
						</view>

						<view class="edit_input">
							<view class="input_box">
								<view class="input">
									<u--input
										v-model="appKeyword"
										placeholder="请选择正确名称"
										border="bottom"
										clearable
										@input="searchApp()"
									></u--input>
								</view>
								<view class="create_btn" @click="updateApp">提交</view>
							</view>
						</view>

						<!-- 备选项列表 -->
						<view class="">
							<view class="edit_list">
								<view class="list">
									<view
										class="item"
										v-for="(item, index) in appletList"
										:key="index"
										@click="handleAppItem(item.article)"
									>
										<text>{{ item.article.title }}</text>
										<text style="font-size: 28rpx;color: #AAAAAA;">{{ item.count }}人相同提交</text>
									</view>
								</view>
							</view>
						</view>

						<view v-if="showAppList">
							<view class="loading" v-if="appLoading"><u-loading-icon></u-loading-icon></view>
							<view class="edit_list" v-else>
								<view class="list">
									<view
										class="item"
										v-for="item in articlesList"
										:key="item.id"
										@click="handleAppItem(item)"
									>
										<text>{{ item.title }}</text>
									</view>
								</view>
							</view>
						</view>
					</view>

					<view class="" v-if="isSuccess">
						<view class="edit_top">
							<view class="title"></view>
							<view class="icon">
								<uni-icons
									type="closeempty"
									size="40rpx"
									@click="$refs.appPopupEdit.close()"
								></uni-icons>
							</view>
						</view>
						<view class="success_main">
							<image
								src="../../static/result-ico.png"
								style="width: 120rpx;height: 120rpx;margin-bottom: 40rpx;"
								mode="widthFix"
							></image>
							<view v-if="appKeyword">已提交修改为“{{ appKeyword }}”，感谢您的贡献！</view>
							<view v-else>提交成功，感谢您的贡献！</view>
							<view style="width: 602rpx;height: 2rpx;background: #EFEFEF;margin: 40rpx 0;"></view>
							<view class="users">
								<text style="color: #A0A0A0;">相同反馈（达到一定数量后生效）：</text>
								<view
									style="display: inline-block;"
									v-for="(item, index) in appUpdateData"
									:key="item.id"
								>
									<text v-if="index != 'type'">
										{{ index == 0 ? item.user.nick_name : ',' + item.user.nick_name }}
									</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</uni-popup>

			<!-- 添加新标签弹窗 -->
			<uni-popup ref="tagPopupEdit" type="bottom" :safe-area="false">
				<view class="edit_popup">
					<view class="edit_top">
						<view class="title">添加新标签</view>
						<view class="icon">
							<uni-icons type="closeempty" size="40rpx" @click="$refs.tagPopupEdit.close()"></uni-icons>
						</view>
					</view>

					<view class="edit_input">
						<view class="input_box">
							<view class="input">
								<u--input
									v-model="tagKeyword"
									placeholder="请选择输入标签名"
									border="bottom"
									clearable
									@input="searchTag()"
								></u--input>
							</view>
							<view class="create_btn" @click="addTag">提交</view>
						</view>
					</view>

					<view v-if="showTagList">
						<view class="loading" v-if="tagLoading"><u-loading-icon></u-loading-icon></view>
						<view class="edit_list" v-else>
							<view class="list">
								<view
									class="item"
									v-for="(item, index) in tagList"
									:key="index"
									@click="handleTagItem(item)"
								>
									<text>{{ item.name }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</uni-popup>

			<!-- 提示删除成功弹窗 -->
			<uni-popup ref="popupDel" type="bottom" :safe-area="false">
				<view class="edit_popup">
					<view class="edit_top">
						<view class="title"></view>
						<view class="icon">
							<uni-icons type="closeempty" size="40rpx" @click="$refs.popupDel.close()"></uni-icons>
						</view>
					</view>
					<view class="success_main">
						<image
							src="../../static/result-ico.png"
							style="width: 120rpx;height: 120rpx;margin-bottom: 40rpx;"
							mode="widthFix"
						></image>
						<view v-if="currentDelTagName">已提交删除“{{ currentDelTagName }}”，感谢您的贡献！</view>
						<view v-else>删除成功，感谢您的贡献！</view>
						<view style="width: 602rpx;height: 2rpx;background: #EFEFEF;margin: 40rpx 0;"></view>
						<view class="users">
							<text style="color: #A0A0A0;">相同反馈（达到一定数量后生效）：</text>
							<view
								style="display: inline-block;"
								v-for="(item, index) in tagUpdateData"
								:key="item.id"
							>
								<text v-if="index != 'type'">
									{{ index == 0 ? item.user.nick_name : ',' + item.user.nick_name }}
								</text>
							</view>
						</view>
					</view>
				</view>
			</uni-popup>

			<!-- 删除标签弹窗 -->
			<u-modal
				:show="showDelModal"
				:content="`确定删除“${currentDelTagName}”的标签？`"
				showCancelButton
				closeOnClickOverlay
				:asyncClose="true"
				@close="showDelModal = false"
				@cancel="showDelModal = false"
				@confirm="delTag"
			></u-modal>
		</view>
	</view>
</template>

<script>
import api from '@/common/api.js';
import waterfallsFlow from '@/components/maramlee-waterfalls-flow/maramlee-waterfalls-flow.vue';
import TagsPopup from '@/components/TagsPopup.vue';
import TopNav from '@/components/TopNav/TopNav.vue';
import qs from 'qs';
import Tag from '@/components/Tag/Tag.vue';
export default {
	name: 'ImageDetail',
	components: {
		TagsPopup,
		waterfallsFlow,
		TopNav,
		Tag,
	},
	props: {
		imgItem: {
			type: Object,
			default: () => {
				return {};
			}
		},
		index: {
			type: Number,
			default: 0
		},
		active: {
			type: Number,
			default: 0
		}
	},
	data() {
		return {
			imgUrl: '', // 图片
			imgId: '', // 图片id
			appName: '', // app名称
			article_id: '', // 文章id
			category: '', // 分类名称
			newCategoryId: '', // 修改后的分类id
			oldCategoryId: '', // 分类id
			tags: [], // 图片标签
			itemHeight: 0,
			style: {},
			show: false,
			assetTags: [], // 所有图片标签
			selectedTags: [],
			page: 1,
			limit: 10,
			list: [],
			proUrl: 'https://api.protograph.cn/', // 正式服地址
			scrollTop: 0,
			moreLoading: 'more',
			showLoading: false,
			newCollect: [],
			allCollect: [],
			folderName: '',
			keepIds: '',
			pageLoading: false,
			tagName: '',
			showWaterfall: true,
			favoriteStatus: false, // 收藏状态
			favoriteId: '', // 当前图片的收藏夹id
			isEdit: false, // 开启编辑状态
			categoriesName: '', // 分类名称
			categoriesList: [], // 分类列表
			showCategoriesList: false, // 显示分类列表
			categoriesLoading: false,
			isSuccess: false, // 是否提交成功
			appKeyword: '', // 搜索app名称
			articlesList: [], // 文章列表（app列表）
			appLoading: false,
			showAppList: false, // 显示app列表
			categoryUpdateData: [], // 分类修改后返回的数据
			appUpdateData: [], // app名称修改后返回的数据
			tagUpdateData: [], // 标签删除后返回的数据
			appletList: [], // app备选项列表
			tagKeyword: '', // 搜索标签名
			showTagList: false,
			tagList: [], // 搜索标签列表
			tagLoading: false,
			showDelModal: false,
			currentDelTagId: '', // 当前要删除的标签id
			currentDelTagName: '' // 当前要删除的标签名称
		};
	},
	onUnload() {
		// 移除监听事件
		// uni.$off('handleImg');
	},
	onReady() {
		// console.log('onReady' + this.index);
		// console.log('tags ==>', this.tags);
		// console.log('active ==>', this.active);
		// console.log('status ==>', this.imgItem);
		if (this.imgItem) {
			this.imgUrl = this.imgItem.medium_url;
			this.imgId = this.imgItem.id;
			this.appName = this.imgItem.name;
		}

		if (this.active >= this.index && this.active - 1 <= this.index) {
			this.list = [];
			this.$refs.waterfallsFlow.refresh();
			this.page = 1;
			this.keepIds = this.imgId;
			this.getAssetsDetail();
			this.getNewFolder();
			this.getAllFolder();
		}
	},
	onShareAppMessage(res) {
		// console.log('share1 ==>', res);
		if (res.from === 'button') {
			// 来自页面内分享按钮
			// console.log(res.target);
		}
		return {
			title: '最全的APP截图收集站',
			path: '/components/ImageDetail2/ImageDetail2'
		};
	},
	watch: {
		active: {
			handler(val) {
				if (val == this.index) {
					// console.log('keep ==>', this.keepIds);
					if (this.keepIds != this.imgId) {
						// console.log('activeVal ==>', val);
						// console.log('tags ==>', this.tags);
						// console.log('id ==>', this.imgId);
						this.list = [];
						this.$refs.waterfallsFlow.refresh();
						this.page = 1;
						this.keepIds = this.imgId;
						this.getAssetsDetail();
						this.getNewFolder();
						this.getAllFolder();
					}
				}
			}
		}
	},
	computed: {
		newFolder() {
			return this.$store.state.newFolder;
		},
		allFolder() {
			return this.$store.state.allFolder;
		}
	},
	methods: {
		async getAssetsDetail() {
			let tokenString = uni.getStorageSync('access_token');
			let url = '';
			if (tokenString) {
				url = api.assetDetailToken.replace(new RegExp('{id}', 'g'), this.imgId);
			} else {
				url = api.assetDetail.replace(new RegExp('{id}', 'g'), this.imgId);
			}
			try {
				let res = await this.$ajax.get({
					url,
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log('res ==>', res);
				let data = res.data.data;
				// 收藏状态
				if (data.favorites && data.favorites.length) {
					this.favoriteStatus = true;
					this.favoriteId = data.favorites[0].id;
					// console.log('this.favoriteId ==>', this.favoriteId);
				} else {
					this.favoriteStatus = false;
				}
				// this.avatar = data.user.avatar;
				// this.nickName = data.user.nick_name;
				// this.imgUrl = this.getAssetUrl(data.medium_url);
				// this.bigUrl = this.getAssetUrl(data.big_url);
				this.tags = data.tags;
				this.article_id = data.article_id;
				this.appName = data.name;
				this.category = data.article.tags[0].name;
				this.oldCategoryId = data.article.tags[0].id;
				this.getMoreAsset();
			} catch (e) {
				console.log(e);
			}
		},

		share() {
			uni.onShareAppMessage({});
		},

		lower(e) {
			if (this.list.length >= this.limit && !this.showLoading) {
				console.log('触底');
				this.page++;
				this.showLoading = true;
				this.moreLoading = 'loading';
				this.getMoreAsset();
			}
		},

		handlePreview() {
			uni.previewImage({
				urls: [this.imgUrl]
			});
		},

		finish(tags) {
			this.tags = tags;
			this.show = false;
		},
		close() {
			this.show = false;
		},

		// 保存图片到相册
		saveImage() {
			uni.getSetting({
				//获取用户的当前设置
				success: res => {
					// console.log('用户当前设置 ==>', res);
					if (res.authSetting['scope.writePhotosAlbum']) {
						//验证用户是否授权可以访问相册
						this.saveImageToPhotosAlbum();
					} else {
						uni.authorize({
							//如果没有授权，向用户发起请求
							scope: 'scope.writePhotosAlbum',
							success: () => {
								this.saveImageToPhotosAlbum();
							},
							fail: () => {
								uni.showToast({
									title: '请打开保存相册权限，再点下载',
									icon: 'none',
									duration: 3000
								});
								setTimeout(() => {
									uni.openSetting({
										//调起客户端小程序设置界面,让用户开启访问相册
										success: res2 => {
											// console.log(res2.authSetting)
										}
									});
								}, 3000);
							}
						});
					}
				}
			});
		},

		// 保存图片到手机相册
		saveImageToPhotosAlbum() {
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			uni.getImageInfo({
				src: this.imgUrl,
				success: res => {
					// console.log('图片信息 ==>', res);
					uni.saveImageToPhotosAlbum({
						filePath: res.path,
						success: res2 => {
							uni.hideLoading();
							uni.showToast({
								title: '图片已保存至相册',
								icon: 'none',
								duration: 2000
							});
						},
						fail: err => {
							uni.hideLoading();
							console.log(err.errMsg);
						}
					});
				},
				fail: err => {
					uni.hideLoading();
				}
			});
		},

		// 获取更多类型图片
		async getMoreAsset() {
			if (this.tags.length <= 0) {
				this.moreLoading = 'noMore';
				this.showLoading = false;
				return;
			}
			let tags = this.tags.map(item => {
				return item.id;
			});
			try {
				let res = await this.$ajax({
					url: api.asset,
					method: 'POST',
					data: {
						tags,
						_page: this.page,
						_limit: this.limit
					}
				});
				// console.log('moreRes ==>', res);
				let data = res.data.data;
				data.forEach((item, index) => {
					// if (item.url.includes('2022')) {
					// 	item.small_url = this.$baseURL + '/' + item.small_url;
					// 	item.url = this.$baseURL + '/' + item.url;
					// } else {
					// 	item.small_url = this.proUrl + item.small_url;
					// 	item.url = this.proUrl + item.url;
					// }
					item.small_url = this.$baseURL + item.small_url;
					item.medium_url = this.$baseURL + item.medium_url;
					item.big_url = this.$baseURL + item.big_url;
				});
				this.list.push(...data);
				// console.log('list ==>', this.list);
				// this.showWaterfall = false;
				// this.$nextTick(() => {
				// 	this.showWaterfall = true;
				// })
				if (data.length < this.limit) {
					this.moreLoading = 'noMore';
				} else {
					this.showLoading = false;
					this.moreLoading = 'more';
				}
			} catch (e) {
				console.log(e);
				this.showLoading = false;
				this.moreLoading = 'more';
			}
		},

		// 点击更多类型图片
		handleImg(e) {
			// console.log('img ==>', e.item);
			let list = this.list.slice(e.item.index - 5 < 0 ? 0 : e.item.index - 5, e.item.index + 5);
			let active = 0;
			list.forEach((item, index) => {
				if (item.id == e.item.id) {
					active = index;
				}
			});
			// console.log('最终列表 ==>', list);
			uni.navigateTo({
				url: `../ImageDetail2/ImageDetail2?active=${active}`,
				animationType: 'slide-out-right',
				success: res => {
					res.eventChannel.emit('handleImg', { imgData: e.item, imgList: list });
				}
			});
		},

		// 获取最新收藏夹
		async getNewFolder() {
			let tokenString = uni.getStorageSync('access_token');
			if (!tokenString) {
				return false;
			}
			try {
				let res = await this.$ajax.get({
					url: api.newest_favorites,
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log('最新收藏夹res ==>', res);
				let data = res.data.data;
				data.forEach(item => {
					if (item.cover_path) {
						item.cover_path = JSON.parse(item.cover_path);
					}
				});
				if (res.statusCode == 200) {
					this.$store.commit('getNewFolder', data || []);
				}
			} catch (e) {
				console.log(e);
			}
		},

		// 获取全部收藏夹
		async getAllFolder() {
			let tokenString = uni.getStorageSync('access_token');
			if (!tokenString) {
				return false;
			}
			try {
				let res = await this.$ajax.get({
					url: api.favoriteFolders,
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log('全部收藏夹res ==>', res);
				let data = res.data.data;
				data.forEach(item => {
					if (item.cover_path) {
						item.cover_path = JSON.parse(item.cover_path);
					}
				});
				if (res.statusCode == 200) {
					this.$store.commit('getAllFolder', data || []);
				}
			} catch (e) {
				console.log(e);
			}
		},

		// 收藏
		collect() {
			let tokenString = uni.getStorageSync('access_token');
			if (!tokenString) {
				console.log('token不存在');
				return uni.navigateTo({
					url: '../../pages/loginWays/loginWays'
				});
			}
			this.$refs.popup.open();
		},

		// 创建收藏夹
		async createFolder() {
			uni.showLoading({
				title: '加载中'
			});
			let tokenString = uni.getStorageSync('access_token');
			try {
				let res = await this.$ajax.post({
					url: api.createFolder,
					data: {
						name: this.folderName
					},
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log('创建收藏夹res ==>', res);
				if (res.statusCode == 200) {
					let data = res.data.data;
					this.$store.commit('addFolder', { id: data.id, name: data.name });
					this.folderName = '';
					uni.hideLoading();
					uni.showToast({
						title: '创建成功',
						icon: 'success'
					});
				} else {
					uni.hideLoading();
					uni.showToast({
						title: '创建失败',
						icon: 'error'
					});
				}
			} catch (e) {
				uni.hideLoading();
				console.log(e);
			}
		},

		// 收藏图片到收藏夹
		async collectAsset(folder_id) {
			uni.showLoading({
				title: '加载中'
			});
			let tokenString = uni.getStorageSync('access_token');
			try {
				let res = await this.$ajax.post({
					url: api.collect,
					data: {
						asset_id: this.imgId,
						folder_id
					},
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log('收藏成功res ==>', res);
				if (res.statusCode == 200) {
					this.favoriteStatus = true;
					this.favoriteId = folder_id;
					this.$refs.popup.close();
					uni.hideLoading();
					uni.showToast({
						title: '收藏成功',
						icon: 'success'
					});
				} else {
					uni.hideLoading();
					uni.showToast({
						title: '收藏失败',
						icon: 'error'
					});
				}
			} catch (e) {
				uni.hideLoading();
				console.log(e);
			}
		},

		// 点击标签
		clickTag(name) {
			uni.navigateTo({
				url: '../../pages/search/search?tag=' + name
			});
			// this.tagName = name;
			// this.$refs.popupFind.open();
			// this.tags = [id];
			// this.getMoreAsset();
		},

		// 获取图片地址
		getAssetUrl(url) {
			return this.$baseURL + url;
		},

		// 取消收藏
		async cancelCollect() {
			// 判断token字符串是否存在
			let tokenString = uni.getStorageSync('access_token');
			if (!tokenString) {
				console.log('token不存在');
				return uni.navigateTo({
					url: '../../pages/loginWays/loginWays'
				});
			}
			try {
				let res = await this.$ajax.delete({
					url: api.del_assets,
					data: {
						folder_id: this.favoriteId,
						asset_ids: [this.imgId]
					},
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log(res);
				if (res.statusCode == 200) {
					this.favoriteStatus = false;
					this.getNewFolder();
					this.getAllFolder();
					uni.showToast({
						title: '已从你的收藏夹中移除!',
						icon: 'none'
					});
				}
			} catch (e) {
				console.log(e);
			}
		},

		handleEdit() {
			// 判断token字符串是否存在
			let tokenString = uni.getStorageSync('access_token');
			if (!tokenString) {
				console.log('token不存在');
				return uni.navigateTo({
					url: '../../pages/loginWays/loginWays'
				});
			}
			this.isEdit = true;
		},

		// 获取备选项
		async getApplet() {
			let tokenString = uni.getStorageSync('access_token');
			try {
				let res = await this.$ajax.get({
					url: api.appletName,
					data: {
						belong_id: this.article_id,
						relation_id: this.imgId
					},
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log('备选项res ==>', res);
				this.appletList = res.data.data;
			} catch (e) {
				console.log(e);
			}
		},

		// 搜索分类
		search() {
			this.showCategoriesList = true;
			clearTimeout(this.timeout);
			this.timeout = null;
			this.timeout = setTimeout(() => {
				this.categoriesList = [];
				this.getClassification(this.categoriesName);
			}, 500);

			if (!this.categoriesName) {
				// this.categoriesList = [];
				this.showCategoriesList = false;
			}
		},

		// 搜索app
		searchApp() {
			this.showAppList = true;
			clearTimeout(this.timeout);
			this.timeout = null;
			this.timeout = setTimeout(() => {
				this.articlesList = [];
				this.getArticlesList(this.appKeyword);
			}, 500);

			if (!this.appKeyword) {
				// this.articlesList = [];
				this.showAppList = false;
			}
		},

		// 搜索app
		searchTag() {
			this.showTagList = true;
			clearTimeout(this.timeout);
			this.timeout = null;
			this.timeout = setTimeout(() => {
				this.tagList = [];
				this.getTags(this.tagKeyword);
			}, 500);

			if (!this.tagKeyword) {
				this.showTagList = false;
			}
		},

		// 获取文章分类
		async getClassification(keyword) {
			if (!keyword) return;
			// 判断token字符串是否存在
			let tokenString = uni.getStorageSync('access_token');
			if (!tokenString) {
				console.log('token不存在');
				return uni.navigateTo({
					url: '../loginWays/loginWays'
				});
			}
			this.categoriesLoading = true;
			try {
				let res = await this.$ajax({
					url: api.getClassification,
					data: {
						_keyword: keyword
					},
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log('searchRes ==>', res);
				this.categoriesList = res.data.data;
				this.$nextTick(() => {
					this.categoriesLoading = false;
				});
				if (this.categoriesList.length <= 0) {
					this.showCategoriesList = false;
				}
			} catch (e) {
				console.log(e);
				this.categoriesLoading = false;
			}
		},

		// 获取文章列表
		async getArticlesList(keyword) {
			if (!keyword) return;
			// 判断token字符串是否存在
			let tokenString = uni.getStorageSync('access_token');
			if (!tokenString) {
				console.log('token不存在');
				return uni.navigateTo({
					url: '../loginWays/loginWays'
				});
			}

			this.appLoading = true;
			try {
				let res = await this.$ajax({
					url: api.get_article_list,
					data: {
						_keyword: keyword
					},
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log('searchRes ==>', res);
				this.articlesList = res.data.data;
				// this.articlesList = data.map(item => {
				// 	return item.title;
				// })
				this.$nextTick(() => {
					this.appLoading = false;
				});
				if (this.articlesList.length <= 0) {
					this.showAppList = false;
				}
			} catch (e) {
				console.log(e);
				this.appLoading = false;
			}
		},

		// 获取所有标签
		async getTags(keyword) {
			if (!keyword) return;
			this.tagLoading = true;
			try {
				let res = await this.$ajax({
					url: api.tags,
					data: {
						_keyword: keyword
					}
				});
				// console.log('resTags ==>', res);
				let data = res.data.data;
				this.tagList = data.asset_tags;
				this.$nextTick(() => {
					this.tagLoading = false;
				});
			} catch (e) {
				this.tagLoading = false;
				console.log(e);
			}
		},

		// 分类、app、标签是否可修改
		async isUpdate(type, item) {
			uni.showLoading({
				title: '加载中'
			});
			let tokenString = uni.getStorageSync('access_token');
			let params;
			if (type === '1') {
				params = {
					type,
					belong_id: this.oldCategoryId,
					relation_id: this.article_id
				};
			} else if (type === '2') {
				params = {
					type,
					belong_id: this.article_id,
					relation_id: this.imgId
				};
			} else if (type === '3' && item) {
				params = {
					type,
					belong_id: item.id,
					relation_id: this.imgId
				};
			}

			try {
				let res = await this.$ajax({
					url: api.isUpdate,
					data: params,
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log('isUpdateRes ==>', res);
				this.isSuccess = res.data.data.type;
				uni.hideLoading();
				if (type === '1') {
					this.$refs.popupEdit.open();
					this.categoryUpdateData = res.data.data;
				} else if (type === '2') {
					this.$refs.appPopupEdit.open();
					this.appUpdateData = res.data.data;
					this.getApplet();
				} else if (type == '3') {
					// console.log('item ==>', item);
					this.currentDelTagId = item.id;
					this.currentDelTagName = item.name;
					if (this.isSuccess) {
						this.$refs.popupDel.open();
						this.tagUpdateData = res.data.data;
						console.log('tagUpdateData,', this.tagUpdateData);
					} else {
						this.showDelModal = true;
					}
				}
			} catch (e) {
				//TODO handle the exception
				uni.hideLoading();
				uni.showToast({
					title: e.message
				});
			}
		},

		// 选择分类
		handleCategorysItem(item) {
			this.categoriesName = item.name;
			this.newCategoryId = item.id;
			this.showCategoriesList = false;
		},

		// 选择app
		handleAppItem(item) {
			this.appKeyword = item.title;
			this.showAppList = false;
		},

		// 选择标签
		handleTagItem(item) {
			this.tagKeyword = item.name;
			this.showTagList = false;
		},

		// 提交修改分类
		async updateCategories() {
			uni.showLoading({
				title: '加载中'
			});
			let tokenString = uni.getStorageSync('access_token');
			try {
				let res = await this.$ajax.put(
					api.assetUpdate,
					{
						target_id: this.newCategoryId,
						type: '1',
						belong_id: this.oldCategoryId,
						relation_id: this.article_id
					},
					{
						header: {
							Authorization: 'Bearer ' + tokenString
						}
					}
				);
				// console.log('修改分类res ==>', res);
				uni.hideLoading();
				this.categoryUpdateData = res.data.data;
				if (res.data.data.length >= 10) {
					this.category = this.categoriesName;
				}
				this.isSuccess = true;
				// this.showPrompt = true;
			} catch (e) {
				uni.hideLoading();
				console.log(e);
			}
		},

		// 提交修改app名称
		async updateApp() {
			uni.showLoading({
				title: '加载中'
			});
			let tokenString = uni.getStorageSync('access_token');
			try {
				let res = await this.$ajax.put(
					api.assetUpdate,
					{
						target_id: '',
						type: '2',
						belong_id: this.article_id,
						relation_id: this.imgId,
						name: this.appKeyword
					},
					{
						header: {
							Authorization: 'Bearer ' + tokenString
						}
					}
				);
				// console.log('修改app名称res ==>', res);
				uni.hideLoading();
				this.appUpdateData = res.data.data;
				if (res.data.data.length >= 10) {
					this.category = this.categoriesName;
				}
				this.isSuccess = true;
				// this.showPrompt = true;
			} catch (e) {
				uni.hideLoading();
				console.log(e);
			}
		},

		// 提交新增标签
		async addTag() {
			uni.showLoading({
				title: '加载中'
			});
			let tokenString = uni.getStorageSync('access_token');
			let url = api.addTags.replace(new RegExp('{id}', 'g'), this.imgId);
			try {
				let res = await this.$ajax.put(
					url,
					{
						tags: [this.tagKeyword]
					},
					{
						header: {
							Authorization: 'Bearer ' + tokenString
						}
					}
				);
				// console.log('修改app名称res ==>', res);
				uni.hideLoading();
				this.$refs.tagPopupEdit.close();
				let flag = true;
				this.tags.forEach(item => {
					if (item.name == this.tagVal) {
						flag = false;
					}
				});
				if (!flag) return;
				this.tags.push({ name: this.tagKeyword });
			} catch (e) {
				uni.hideLoading();
				console.log(e);
			}
		},

		// 删除标签
		async delTag() {
			let tokenString = uni.getStorageSync('access_token');
			try {
				let res = await this.$ajax.put(
					api.assetUpdate,
					{
						target_id: this.currentDelTagId,
						type: '3',
						belong_id: this.currentDelTagId,
						relation_id: this.imgId
					},
					{
						header: {
							Authorization: 'Bearer ' + tokenString
						}
					}
				);
				// console.log('删除标签res ==>', res);
				this.tagUpdateData = res.data.data;
				this.showDelModal = false;
				this.$refs.popupDel.open();
				if (res.data.data.length >= 10) {
					let index = _this.picArr.findIndex(item => {
						return item.id === this.currentDelTagId;
					});
					this.tags.splice(index, 1);
				}
			} catch (e) {
				this.showDelModal = false;
				console.log(e);
			}
		}
	}
};
</script>

<style lang="scss">
$font-color: #111;
.ImageDetail {
	background-color: $font-color;
	// padding-top: 40rpx;
	// height: 100vh;
	// overflow: auto;
	.content {
		background-color: $font-color;
	}
	.scroll {
		height: 100vh;
	}
	.img_box {
		position: relative;
		border-radius: 50rpx 50rpx 0 0;
		overflow: hidden;
	}
	.img {
		font-size: 0;
	}
	.img_mask {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(
			rgba(0, 0, 0, 0.3),
			rgba(0, 0, 0, 0) 22%,
			rgba(0, 0, 0, 0.04),
			rgba(0, 0, 0, 0.3) 150%
		);
	}
	.toolbar {
		// height: 200rpx;
		padding: 20rpx 20rpx 60rpx;
		background-color: #fff;
	}
	.sticky {
		position: sticky;
		bottom: -40rpx;
		border-radius: 0 0 50rpx 50rpx;
		overflow: hidden;
	}
	.add_btn {
		margin: 0 10rpx 10rpx 0;
	}
	.tags {
		margin-bottom: 40rpx;
	}
	.tag_list {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-wrap: wrap;
	}
	.tag_item {
		display: inline-block;
		margin: 0 10rpx 10rpx 0;
		border-radius: 12rpx;
		overflow: hidden;
	}
	.tag_icon {
		margin-left: 10rpx;
	}
	.btns {
		display: flex;
		justify-content: center;
		position: relative;
	}
	.collect {
		background-color: #efefef;
		color: $font-color;
		margin-right: 16rpx;
	}
	.save {
		background-color: #1890ff;
		color: #fff;
	}
	.img_btn {
		width: 132rpx;
		height: 96rpx;
		text-align: center;
		line-height: 96rpx;
		border-radius: 48rpx;
	}
	.more {
		border-radius: 50rpx 50rpx 0 0;
		background-color: #fff;
		margin-top: 4rpx;
	}
	.more_title {
		font-size: 36rpx;
		font-weight: bold;
		color: $font-color;
		text-align: center;
		padding: 40rpx 0;
	}
	.more_list {
		min-height: 800rpx;
		position: relative;
		padding: 20rpx 20rpx 0;
		// background-color: #f5f5f5;
	}
	.list_loading {
		background-color: #fff;
	}
	.more_loading {
		height: 80rpx;
		background-color: #fff;
	}

	/* 收藏弹出层 */
	.collect_popup {
		max-height: 90vh;
		overflow-y: auto;
		border-radius: 60rpx 60rpx 0 0;
		background-color: #fff;
	}
	.collect_top {
		position: sticky;
		top: 0;
		padding: 40rpx;
		border-bottom: 2rpx solid #f4f4f2;
		background-color: #fff;
		z-index: 2;
		.icon {
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
			right: 40rpx;
			color: #000;
			font-weight: 700;
		}
	}
	.collect_list {
		background-color: #fff;
		padding: 20rpx;
		padding-bottom: 0;
		font-size: 36rpx;
		letter-spacing: 2rpx;
		.title {
			font-size: 28rpx;
			color: #888;
			margin-bottom: 20rpx;
		}
		.list {
			width: 100%;
			// padding-left: 30rpx;
			box-sizing: border-box;
			font-size: 32rpx;
			// background-color: #e6f7ff;
		}
	}
	.collect_item {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
		padding: 10rpx 0;
	}
	.create_folder {
		// height: 100rpx;
		// padding: 20rpx;
		// box-sizing: border-box;
		// background-color: #f1f1f1;
	}
	.input_box {
		display: flex;
		align-items: center;
		justify-content: center;
		// height: 160rpx;
		background-color: #fff;
		padding: 0 20rpx 50rpx;
		.input {
			flex: 1;
		}
	}
	.create_btn {
		width: 100rpx;
		height: 77rpx;
		background-color: #3c9cff;
		margin-left: 20rpx;
		color: #ffffff;
		border-radius: 36rpx;
		text-align: center;
		line-height: 77rpx;
		font-size: 28rpx;
	}

	.cover {
		position: relative;
		display: flex;
		align-items: center;
		width: 80rpx;
		height: 80rpx;
		border-radius: 20rpx;
		overflow: hidden;
		margin-right: 20rpx;
		background-color: #eee;
		z-index: 10;
	}

	.cover::after {
		content: '';
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 20;
		background-color: rgba(0, 0, 0, 0.04);
		border-radius: 20rpx;
	}

	.back {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		// background-color: #fff;
		border-radius: 50%;
		overflow: hidden;
		font-weight: 700;
	}

	.share_btn {
		width: 60rpx;
		height: 60rpx;
		background-color: #fff;
		position: absolute;
		left: 0;
		top: 50%;
		transform: translateY(-50%);
		display: flex;
		justify-content: center;
		border: none;
		margin-left: 20rpx;
	}

	.edit_btn,
	.back_btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		position: absolute;
		right: 20rpx;
		top: 20rpx;
		border-radius: 50%;
	}
	.edit_btn {
		background-color: #f2f2f2;
	}
	/* 收藏弹出层end */

	/* 编辑弹出层 */
	.edit_popup {
		max-height: 90vh;
		height: 90vh;
		overflow-y: auto;
		border-radius: 60rpx 60rpx 0 0;
		background-color: #fff;
	}
	.edit_top {
		position: sticky;
		top: 0;
		padding: 40rpx;
		background-color: #fff;
		z-index: 2;
		.icon {
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
			right: 40rpx;
			color: #000;
			font-weight: 700;
		}
		.title {
			min-height: 40rpx;
		}
	}
	.edit_list {
		background-color: #fff;
		padding: 0 20rpx;
		font-size: 36rpx;
		letter-spacing: 2rpx;
		.list {
			width: 100%;
			// padding-left: 30rpx;
			box-sizing: border-box;
			font-size: 32rpx;
			// background-color: #e6f7ff;
		}
		.item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 20rpx;
			margin-bottom: 40rpx;
		}
	}
	.edit_item {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
		padding: 10rpx 0;
	}
	.edit_input {
		position: sticky;
		top: 122rpx;
	}
	.edit_input .input_box {
		display: flex;
		align-items: center;
		justify-content: center;
		// height: 160rpx;
		background-color: #fff;
		padding: 0 20rpx 50rpx;
		.input {
			flex: 1;
		}
	}
	.loading {
		height: calc(90vh - 248rpx);
		display: flex;
		align-items: center;
		justify-content: center;
	}
	/* 编辑弹出层end */

	/* 编辑成功提示 */
	.success_main {
		display: flex;
		flex-direction: column;
		align-items: center;
		.users {
			width: 612rpx;
			font-size: 24rpx;
		}
	}
	/* 编辑成功提示end */

	.Tag {
		height: 64rpx;
		background-color: #f2f2f2;
		border-radius: 32rpx;
		text-align: center;
		line-height: 64rpx;
		font-size: 28rpx;
		color: #1890ff;
		padding: 0 24rpx;
	}
	.tag-wrap {
		display: flex;
		align-items: center;
	}
	// .popup_find {
	// 	// position: relative;
	// 	width: 100%;
	// 	height: 90vh;
	// 	border-radius: 40rpx 40rpx 0 0;
	// 	background-color: #fff;
	// }
	// .popup_find_top {
	// 	position: relative;
	// 	display: flex;
	// 	justify-content: center;
	// 	align-items: center;
	// 	padding: 40rpx 20rpx;
	// }
	// .popup_find_close {
	// 	position: absolute;
	// 	left: 20rpx;
	// 	top: 36rpx;
	// }
	// .popup_find_title {
	// 	font-size: 36rpx;
	// 	font-weight: 700;
	// }
}
</style>
